var app = angular.module('myApp', ['ngGrid']);
app.controller('MyCtrl', function($scope, $http) {
	csvOpts = { columnOverrides: { obj: function(o) {
	 return o.a + '|' +  o.b; }
		 } }

	hgtOpts = { minHeight: 1400 }  ;
    $scope.filterOptions = {
        filterText: "",
        useExternalFilter: true
    };
	
    $scope.totalServerItems = 0;
    $scope.pagingOptions = {
        pageSizes: [10, 20],
        pageSize: 10,
        currentPage: 1
    };  
    $scope.setPagingData = function(data, page, pageSize){	
        var pagedData = data.slice((page - 1) * pageSize, page * pageSize);
        $scope.myData = pagedData;
        $scope.totalServerItems = data.length;
        if (!$scope.$$phase) {
            $scope.$apply();
        }
    };
//Added for editable Column 
  $scope.cellInputEditableTemplate = '<input ng-class="\'colt\' + col.index" ng-input="COL_FIELD" ng-model="COL_FIELD" ng-blur="updateEntity(row)" />';
  $scope.cellSelectEditableTemplate = '<select ng-class="\'colt\' + col.index" ng-input="COL_FIELD" ng-model="COL_FIELD" ng-options="id as name for (id, name) in statuses" ng-blur="updateEntity(row)" />';
    $scope.gridOptions = {
        data: 'myData',
//field should have same name as data in data file		
		columnDefs: [{displayName:'Referenceno', field:'TrnNo', width:"75px"},{displayName:'Customer',field:"custdesc", width:"150px"},{displayName:'Pax Name', field:'PaxName', cellTemplate: '<div>{{row.entity[col.field]}}</div>'},{displayName:'Sector', field:'Sector', width:"75px"},{displayName:'Travel Date',field:'TravelDate'},{displayName:'Base Fare (in Rs)', field:'BaseFare'},{displayName:'Taxes (in Rs)', field:'Taxes'}, {displayName:'Admin charges (in Rs)', field:'Admincharges'},{displayName:'Total Amount (in Rs)',field:'TotalAmount'}, 
		],//{cellTemplate: '<input type="button" name="delete" onclick="admincharges(\'adminchrg.php?id={{row.entity.TrnNo}}&up=true\')" value="Admin Chrg">'}
//		{displayName: 'Admin Chrg', field:'Admincharges', enableCellEditOnFocus: true}],
		plugins: [new ngGridCsvExportPlugin(csvOpts)],
		showGroupPanel: true,
        enablePaging: true,
        showFooter: true,
		enableCellEdit: false,
		enableCellSelection: true,
        enableColumnResize: true,
        totalServerItems:'totalServerItems',
        pagingOptions: $scope.pagingOptions,
        filterOptions: $scope.filterOptions,
		jqueryUITheme: true
    };

  $scope.updateEntity = function(row) {
    if(!$scope.save) {
      $scope.save = { promise: null, pending: false, row: null };
    }
    $scope.save.row = row.rowIndex;
    if(!$scope.save.pending) {
      $scope.save.pending = true;
      $scope.save.promise = $timeout(function(){
        // $scope.list[$scope.save.row].$update();
        console.log("Here you'd save your record to the server, we're updating row: " 
                    + $scope.save.row + " to be: " 
                    + $scope.list[$scope.save.row].adminchrg);
//                    + $scope.list[$scope.save.row].age + ","
//                    + $scope.list[$scope.save.row].status);
        $scope.save.pending = false; 
      }, 500);
    }    
  };
// --	
    $scope.getPagedDataAsync = function (pageSize, page, searchText) {
        setTimeout(function () {
            var data;
            if (searchText) {
                var ft = searchText.toLowerCase();
				alert();
                $http.get("invoicedata.php").success(function (largeLoad) {		
                    data = largeLoad.filter(function(item) {
                        return JSON.stringify(item).toLowerCase().indexOf(ft) != -1;
                    });
                    $scope.setPagingData(data,page,pageSize);
                });            
            } else {
                $http.get("invoicedata.php").success(function (largeLoad) {
                    $scope.setPagingData(largeLoad,page,pageSize);
                });
            }
        }, 100);
    };

		$scope.refreshGrid = function() {
			$scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage);
		};	


    $scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage);
	
    $scope.$watch('pagingOptions', function (newVal, oldVal) {
        if (newVal !== oldVal && newVal.currentPage !== oldVal.currentPage) {
          $scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
        }
    }, true);
    $scope.$watch('filterOptions', function (newVal, oldVal) {
        if (newVal !== oldVal) {
          $scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
        }
    }, true);
	
	
//  $scope.addRow = function() {
//      $scope.myData.push({Referenceno: "Auto Nomber", Date: "2013-01-01", Sub_Category: "Sub Cat", Business: "Business", Dist_Name: "Customer", Sub_delear: "Sub Delear", Dr_Amount: "Debit", Cr_Amount: "Credit", Bank: "Bank", Branch: "Branch"});
//    };
});
$scope.directive('ngBlur', function () {
  return function (scope, elem, attrs) {
    elem.bind('blur', function () {
      scope.$apply(attrs.ngBlur);
    });
  };
})

.filter('mapStatus', function( StatusesConstant ) {
  return function(input) {
    if (StatusesConstant[input]) {
      return StatusesConstant[input];
    } else {
      return 'unknown';
    }
  };
})

.factory( 'StatusesConstant', function() {
  return {
    1: 'active',
    2: 'inactive'
  };
});

// Added for Column Save
//app.controller('MainCtrl', function($scope, $timeout, StatusesConstant) {
//  $scope.statuses = StatusesConstant;
//  $scope.cellInputEditableTemplate = '<input ng-class="\'colt\' + col.index" ng-input="COL_FIELD" ng-model="COL_FIELD" ng-blur="updateEntity(row)" />';
//  $scope.cellSelectEditableTemplate = '<select ng-class="\'colt\' + col.index" ng-input="COL_FIELD" ng-model="COL_FIELD" ng-options="id as name for (id, name) in statuses" ng-blur="updateEntity(row)" />';
//
//  $scope.updateEntity = function(row) {
//    if(!$scope.save) {
//      $scope.save = { promise: null, pending: false, row: null };
//    }
//    $scope.save.row = row.rowIndex;
//    if(!$scope.save.pending) {
//      $scope.save.pending = true;
//      $scope.save.promise = $timeout(function(){
//        // $scope.list[$scope.save.row].$update();
//        console.log("Here you'd save your record to the server, we're updating row: " 
//                    + $scope.save.row + " to be: " 
//                    + $scope.list[$scope.save.row].name + "," 
//                    + $scope.list[$scope.save.row].age + ","
//                    + $scope.list[$scope.save.row].status);
//        $scope.save.pending = false; 
//      }, 500);
//    }    
//  };
//})


//.filter('mapStatus', function( StatusesConstant ) {
//  return function(input) {
//    if (StatusesConstant[input]) {
//      return StatusesConstant[input];
//    } else {
//      return 'unknown';
//    }
//  };
//})
//
//.factory( 'StatusesConstant', function() {
//  return {
//    1: 'active',
//    2: 'inactive'
//  };
//});
// JavaScript Document